﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Mapping Application Block
//===============================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using EntLibContrib.Query;
using EntLibContrib.Mapping.QuickStart.DomainObjects;

namespace EntLibContrib.Mapping.QuickStart
{
	/// <summary>
	/// Controller to manage CRUD actions for domain object
	/// </summary>
	/// <remarks>Only handles the Basic1 object at present</remarks>
	public static class DomainObjectController
	{
		#region Static Fields
		private static Guid identityId = new Guid("816dae3c-9bbf-4c5f-9301-bc52575dcf09");
		#endregion

		#region Public Static Methods
		public static ICollection<Basic1> GetBasic1Collection()
		{
			ICollection<Basic1> basic1Collection = MapperFactory.CreateMapper("Basic1 Mapper").ToDomainObjectCollection<Basic1>(QueryFactory.CreateQuery("Read Basic1 All").ExecuteForRead());
			CancelChangesInBasic1Collection(basic1Collection);
			return basic1Collection;
		}

		/// <summary>
		/// Determines whether any of the items in the collection are dirty.
		/// </summary>
		/// <param name="basic1Collection">The basic1 collection.</param>
		/// <returns>
		/// 	<c>true</c> if any item is dirty; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsDirtyBasic1Collection(ICollection<Basic1> basic1Collection)
		{
			foreach (Basic1 basic1 in basic1Collection)
			{
				if (basic1.IsDirty)
					return true;
			}

			return false;
		}

		/// <summary>
		/// Cancels the changes in basic1 collection.
		/// </summary>
		/// <param name="basic1Collection">The basic1 collection.</param>
		public static void CancelChangesInBasic1Collection(ICollection<Basic1> basic1Collection)
		{
			foreach (Basic1 basic1 in basic1Collection)
			{
				basic1.IsDirty = false;
			}
		}

		/// <summary>
		/// Saves the changes in basic1 collection.
		/// </summary>
		/// <param name="basic1Collection">The basic1 collection.</param>
		public static void SaveChangesInBasic1Collection(ICollection<Basic1> basic1Collection)
		{
			Collection<Basic1> dirtyBasic1Collection = new Collection<Basic1>();
			foreach (Basic1 basic1 in basic1Collection)
			{
				if (basic1.IsDirty)
				{
					basic1.IdentityId = identityId;
					dirtyBasic1Collection.Add(basic1);
					basic1.IsDirty = false;
				}
			}
			QueryFactory.CreateQuery("Update Basic1").ExecuteForWrite(MapperFactory.CreateMapper("Basic1 Mapper").FromDomainObjectCollection(dirtyBasic1Collection));
		}
		#endregion
	}
}
